import React, { useEffect, useState } from 'react';
import { View, Image, ScrollView } from '@tarojs/components';
import './index.less';
import CommonPopup from '../commonPopup';
import Taro from '@tarojs/taro';
import { AtSearchBar } from 'taro-ui';
import { associationListFun } from '@/src/common/method/nearbyFun';
import store from '@/src/store';

interface RelatePopupProps {
  /** 是否显示 */
  isShow: boolean;
  /** 关闭回调 */
  onClose: () => void;
  /** 点击拍照识别调用的方法 */
  takeCigaPhoto: () => void;
}

export default function RelatePopup({
  isShow,
  onClose,
  takeCigaPhoto,
}: RelatePopupProps) {
  const [receiveContent, setReceiveContent] = useState<any[]>([]);
  const [pageNo, setPageNo] = useState(1); // 当前页（1 开始）
  const [totalPage, setTotalPage] = useState(1); // 总页数
  const [loading, setLoading] = useState(false); // 正在拉取
  const [hasMore, setHasMore] = useState(true); // 还有更多

  const fetchPage = async (nextPage: number, replace = false) => {
    if (loading) return;
    setLoading(true);
    try {
      const params = {
        pageNo: String(nextPage), // 文档是 string，这里转一下更稳
        pageSize: 10,
        ucUserId: Taro.getStorageSync('userId'),
      };
      const res: any = await associationListFun(params);
      const data = res?.data ?? res;
      const list: any[] = data?.list ?? [];

      const tp = Number(data?.totalPage ?? 1) || 1;
      setTotalPage(tp);

      setReceiveContent((prev) => (replace ? list : prev.concat(list)));

      setPageNo(nextPage);
      setHasMore(nextPage < tp && list.length > 0);
    } catch (e) {
      // 出错时不要疯狂触发 onScrollToLower
      setHasMore(false);
    } finally {
      setLoading(false);
    }
  };

  // 关闭时清空；打开时拉第一页
  useEffect(() => {
    if (!isShow) {
      setReceiveContent([]);
      setPageNo(1);
      setTotalPage(1);
      setHasMore(true);
      setLoading(false);
      return;
    }
    // 首次打开拉第一页
    fetchPage(1, true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isShow]);

  if (!isShow) {
    return null;
  }

  // 关联产品
  const relateProduct = (item: any) => {
    if (item.associationType === 'CIGAR') {
      const data = {
        cigarSku: item.associationId,
        contentCigarBrand: item.associationBrand,
        contentCigarZh: item.associationName,
        contentCigarImg: item.associationImage,
      };
      store.publishStore.setContentCigar(data);
    } else {
      const data = {
        model: item.associationId,
        contentCigarCabinetBrand: item.associationBrand,
        contentCigarCabinetZh: item.associationName,
        contentCigarCabinetImg: item.associationImage,
      };
      store.publishStore.setContentCigarCabinet(data);
    }
    onClose();
  };

  // 右侧接近底部触发
  const handleScrollToLower = () => {
    if (!loading && hasMore) {
      fetchPage(pageNo + 1);
    }
  };
  const gotoDraftBoxPage = () => {
    Taro.navigateTo({
      url: '/subPagesAccount/relateSearch/index',
    });
    onClose();
  };

  const relateContent = () => {
    return (
      <View className="relatePop-container">
        <View className="relatePopup-search" onClick={gotoDraftBoxPage}>
          <AtSearchBar
            placeholder="搜索关联雪茄或雪茄柜"
            showActionButton={false}
            className="relatePopup-search-bar"
            value=""
            onChange={() => {}}
            disabled
          />
        </View>

        <View className="relate-content">
          <View className="relate-content1">
            <View className="relate-content-topic">
              同一类型产品只能关联一个
            </View>
            <View className="relate-content1-main">
              <Image
                src="https://file.linkcook.cn/image/wineMiniProgram/home/egCigar.png"
                className="egCigar"
              />
              <View className="relate-content-tips">请拍摄雪茄正标</View>
              <View className="relate-content-btn">
                <Image
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/camera.png"
                  className="camera"
                />
                <View className="relate-content-btn1" onClick={takeCigaPhoto}>
                  拍照识别雪茄
                </View>
              </View>
            </View>
          </View>

          <View className="relate-content2">
            <View className="relate-content-topic">关联历史记录</View>

            {/* 横向滚动 + 触底加载 */}
            <ScrollView
              className="relate-content-relateHistory"
              scrollX
              enableFlex
              lowerThreshold={120} // 距右边 120px 触发
              onScrollToLower={handleScrollToLower}
            >
              {receiveContent.map((item: any) => (
                <View
                  key={item.associationId}
                  className="relate-content-receiveCigar"
                >
                  <View className="relate-content-cigar">
                    <Image
                      src={item.associationImage}
                      className="content-pic"
                      mode="aspectFit"
                    />
                  </View>
                  <View className="relate-content-name">
                    {`${item.associationBrand} ${item.associationName}`}
                  </View>
                  <View
                    className="relate-content-relateBtn"
                    onClick={() => relateProduct(item)}
                  >
                    关联
                  </View>
                </View>
              ))}

              {/* 尾部：加载状态/没有更多 */}
              <View className="relate-content-tail">
                {loading ? '加载中...' : !hasMore ? '' : null}
              </View>
            </ScrollView>
          </View>
        </View>
      </View>
    );
  };

  return (
    <View>
      <CommonPopup
        visible={isShow}
        onClose={onClose}
        className="ralatePopupClass"
        full={false}
        content={relateContent()}
        title="关联产品"
      />
    </View>
  );
}
